<?php

namespace addons\booking\model;

use think\Model;


class Comment extends Model
{

    // 表名
    protected $name = 'booking_comment';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text'
    ];


    public function getTypeList()
    {
        return ['0' => __('Type 0'), '1' => __('Type 1')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 房间列表
     *
     * @param array $param
     * @return void
     */
    public static function tableList($param)
    {
        $pageNum = 15;
        if (isset($param['num']) && !empty($param['num'])) {
            $pageNum = $param['num'];
        }

        $list = self::with([
            'User'   => function ($query) {
                $query->field('id,nickname,avatar');
            },
            'replay' => [
                'Manage' => function ($query) {
                    $query->field('id,nickname');
                }
            ]
        ])
            ->field('id,type,source_id,user_id,comment,grade,createtime')
            ->where(function ($query) use ($param) {

                $query->where('status', 'normal')->where('pid', 0);

                if (isset($param['type']) && $param['type'] != '') {
                    $query->where('type', $param['type']);
                }

                if (isset($param['source_id']) && !empty($param['source_id'])) {
                    $query->where('source_id', $param['source_id']);
                }
            })->order('createtime desc')->paginate($pageNum);

        foreach ($list as $item) {
            if ($item->user) {
                $item->user->avatar = cdnurl($item->user->avatar, true);
            }
        }
        return $list;
    }


    public function Manage()
    {
        return $this->belongsTo('\app\admin\model\Admin', 'user_id', 'id');
    }

    public function User()
    {
        return $this->belongsTo('\app\common\model\User', 'user_id', 'id');
    }

    public function replay()
    {
        return $this->hasMany('Comment', 'pid', 'id', [], 'LEFT');
    }
}
